﻿using System.Diagnostics;

namespace SmartMotion.Core.Tools
{
    public class IfItem:ActionExpression
    {
        public override ActionResult Run()
        {
            Stopwatch sw = Stopwatch.StartNew();
            State = "...";
            IniState(Nodes);
            Em.GetEvent<RunActionItem>().Publish(this);
            Em.GetEvent<DebugMessage>().Publish($"运行{Name}");
            
            var result = RunMethod();//运行if表达式

            if (BoolResult)//if=true表达式的结果
            {
                foreach (ActionItem actionItem in Nodes)
                {
                    if (actionItem is ElseIfItem || actionItem is ElseItem) break;//执行elseif或else前的节点
                    result = actionItem.Run();
                    if (result == ActionResult.Error) break;

                }
            }
            else
            {
                foreach (ActionItem actionItem in Nodes)
                {
                    if (actionItem is ElseIfItem elseIf) //查找elseif
                    {
                        result = elseIf.Run();
                        if (result == ActionResult.Error) break;
                        if (elseIf.BoolResult)
                        {
                            break;
                        }
                    }
                    if (actionItem is ElseItem elseItem) //查找else
                    {
                        result = elseItem.Run();
                        break;
                    }
                }
            }

            State = ActionResult.Success.ToString();
            Time = (int)sw.ElapsedMilliseconds;
            Em.GetEvent<RunActionItem>().Publish(this);
            return result;
        }

    }

    public class ElseIfItem : ActionExpression
    {
        public override ActionResult Run()
        {
            var result = ActionResult.Success;
            Stopwatch sw = Stopwatch.StartNew();
            State = "...";
            Em.GetEvent<RunActionItem>().Publish(this);
            Em.GetEvent<DebugMessage>().Publish($"运行{Name}");
            result= RunMethod();//运行Else if

            if (result==ActionResult.Success)//编译没问题
            {
                if (BoolResult)//elseif==true
                {
                    foreach (ActionItem actionItem in Nodes) //运行else if分支
                    {
                        result = actionItem.Run();
                        if (result == ActionResult.Error)
                        {
                            break;
                        }
                    }
                }
            }

            State = result.ToString();
            Time = (int)sw.ElapsedMilliseconds;
            Em.GetEvent<RunActionItem>().Publish(this);
            return result;
        }
    }

    public class ElseItem : ActionItem
    {
        protected override ActionResult RunMethod()
        {
            var result = ActionResult.Success;
            return result;
        }
    }

}